/*
 * Copyright 2007 Rob Nielsen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.proxymatic.core.handlers.method;

import com.googlecode.proxymatic.core.AbstractMethodHandler;
import com.googlecode.proxymatic.core.BuildtimeContext;
import com.googlecode.proxymatic.core.MethodInvoker;
import com.googlecode.proxymatic.core.ProxyBuilder;
import com.googlecode.proxymatic.core.RuntimeContext;
import com.googlecode.proxymatic.core.util.ReflectUtil;
import com.googlecode.proxymatic.core.util.StringUtil;

import java.lang.reflect.Method;

/**
 * This handler produces a basic toString message that indicates the type of proxy it is, the interfaces it implements
 * and it's implementation objects.  This handler is added automatically in the baseline HandlerConfiguration but can be
 * replaced if desired.
 */
public class ToStringMethodHandler extends AbstractMethodHandler implements MethodInvoker {
    private static final Method TOSTRING_METHOD = ReflectUtil.getMethod(Object.class, "toString");

    private String name;

    public ToStringMethodHandler() {
        this("Proxy");
    }

    public ToStringMethodHandler(String name) {
        this.name = name;
    }

    public MethodInvoker getInvoker(Method method, BuildtimeContext context, ProxyBuilder proxyBuilder) {
        if (method.equals(TOSTRING_METHOD)) {
            return this;
        } else {
            return NOT_HANDLED;
        }
    }

    public Object invoke(Method method, Object[] parameters, RuntimeContext context) throws Throwable {
        BuildtimeContext buildtimeContext = context.getBuildtimeContext();
        StringBuffer sb = new StringBuffer();
        sb.append(name).append(" implementation of ").append(StringUtil.sentence(buildtimeContext.getTargetInterfaces()));
        if (buildtimeContext.getImplementationClasses().size() > 0) {
            sb.append(" backed by ");
            if (buildtimeContext.isImplementationAvailableAtRuntime()) {
                sb.append(StringUtil.sentence(context.getImplementationObjects()));
            } else {
                sb.append(StringUtil.sentence(buildtimeContext.getImplementationClasses()));
            }
        }
        return sb.toString();
    }

    public Class[] getExceptionTypes() {
        return NO_DECLARED_EXCEPTIONS;
    }
}
